<template>
  <div class="uploadcommoditiesd">
    <van-nav-bar
      title="新闻发布"
      fixed
      placeholder
      right-text="已发布"
      @click-right="onClickRight"
    />

    <div class="main">
      <div class="content">
        <van-uploader v-model="fileList" multiple :max-count="6" />

        <!-- <van-field
          readonly
          clickable
          label="类型"
          :value="value"
          placeholder="选择商品类型"
          @click="showPicker = true"
        /> -->
        <van-popup v-model="showPicker" round position="bottom">
          <van-picker
            show-toolbar
            :columns="columns"
            @cancel="showPicker = false"
            @confirm="onConfirm"
          />
        </van-popup>
        <van-field
          v-model="formData.title"
          label="新闻标题"
          placeholder="请输入新闻标题"
          required
        />
        <!-- <van-field
          v-model="formData.price"
          type="number"
          label="价格"
          placeholder="请输入商品价格"
          required
        /> -->
        <!-- <van-field
          v-model="formData.left"
          type="number"
          label="数量"
          placeholder="请输入商品数量"
          required
        /> -->
        <van-field
          v-model="formData.des"
          rows="2"
          autosize
          label="内容"
          type="textarea"
          placeholder="请输入新闻内容"
          show-word-limit
          required
        />

        <div class="footer">
          <van-button
            type="primary"
            :loading="isLoading"
            :loading-text="isloadingText"
            block
            @click="upload"
            >发布新闻</van-button
          >

          <!-- <van-button type="default" block>取消上传</van-button> -->
          <!-- <div class="reslut" v-for="(item, index) in msg" :key="index">
            {{ item }}
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant"
import { Notify } from "vant"
import client from "./client.js"
import { Dialog } from "vant"
import OSS from "ali-oss"
export default {
  name: "uploadcommoditiesd",

  created() {},

  data() {
    return {
      // 审核token
      token: "",
      files: [],
      readflag: false, //是否读取完成
      isLoading: false,
      isFormDataEmpty: true,
      isloadingText: "",
      formData: {
        pic: "",
        title: "",
        des: "",
      },
      fileList: [],
      image_urls: [],
      msg: [],
      title: "",
      value: "",
      price: "",
      message: "",
      showPicker: false,
      columns: [],
      form: {
        num: 0,
        title: "",
        city: "",
        exhibitionType: "",
        extension: "",
        businessHours: "",
        location: "",
        name: "",
        number: "",
        imgBanner: "",
        img: [],
        content: "",
      },
    }
  },

  methods: {
    beforeRead(file) {
      console.log(file)
    },

    onClickRight() {
      this.$router.push("/hasissued")
    },

    checkFormDataEmpty() {
      const formDataValues = Object.values(this.formData)
      const isAllEmpty = formDataValues.every((value) => value === "")
      console.log(isAllEmpty)
      this.isFormDataEmpty = isAllEmpty
    },

    // 上传前对图片文字进行审核
    async examineBothTwo() {
      let self = this
      await self.$api.uploadcommoditiesd
        .getExamineToken()
        .then((res) => {
          console.log(res)
          let obj = JSON.parse(res.data)
          self.token = obj.access_token
          console.log(self.token)
        })
        .then((res) => {
          let word = [self.formData.title, self.formData.des]
          // 对文字和图片同时审核
          Promise.all([
            self.examinePic(self.token, self.image_urls),
            self.examineWord(self.token, word),
          ]).then((res) => {
            console.log(res)
            let allResluts = []
            res.map((item) => {
              item.data.map((v) => {
                allResluts.push(JSON.parse(v))
              })
            })
            // 这是文字和图片审核所有结果
            console.log(allResluts)
            const result = allResluts.filter((item) => item.conclusionType != 1)
            if (result.length) {
              // 有违规信息
              console.log(result)
              let msg = []
              result.forEach((item) => {
                msg.push(item.data[0].msg)
              })
              console.log(msg)
              self.msg = msg
              // return false
              Toast("审核不通过")
              self.isLoading = false
              self.isloadingText = ""
              let msgStr = self.msg.join(",")
              Dialog.alert({
                title: "上传失败",
                message: msgStr,
              }).then(() => {
                // on close
              })

              let subStr = []
              self.image_urls.forEach((item) => {
                subStr.push(
                  item.split("https://liulin.oss-cn-chengdu.aliyuncs.com/")[1]
                )
              })
              console.log(subStr)
              async function deleteMulti() {
                try {
                  // 填写需要删除的多个Object完整路径并设置返回模式为详细模式。Object完整路径中不能包含Bucket名称。
                  //let result = await client.deleteMulti(['exampleobject-1', 'exampleobject-2', 'testfolder/sampleobject.txt']);
                  //console.log(result);
                  // 填写需要删除的多个Object完整路径并设置返回模式为简单模式。Object完整路径中不能包含Bucket名称。
                  let result = await client.deleteMulti(subStr, {
                    quiet: true,
                  })
                  console.log(result)
                } catch (error) {
                  console.log(error)
                }
              }

              deleteMulti()
            } else {
              // 都合规
              //上传到服务器
              const params = {
                obj: self.formData,
                imgs: JSON.stringify(self.image_urls),
              }

              self.$api.uploadcommoditiesd
                .uploadShopsMsg(params)
                .then((res) => {
                  console.log(res)
                  if ((res.code = 200)) {
                    Toast("提交成功")
                    self.isLoading = false
                    self.isloadingText = ""
                  }
                })
            }
          })
          // .catch((e) => {
          //   Toast(e)
          // })
        })
    },

    // 对图片进行审核
    examinePic(token, imgArr) {
      let params = { token, imgArr }
      console.log(params)
      // if(params.imgArr>2)
      return this.$api.uploadcommoditiesd.examinePic(params)
    },

    // 对文字进行审核
    examineWord(token, wordobj) {
      let params = { token, wordobj }
      return this.$api.uploadcommoditiesd.examineWord(params)
    },

    // 获取picker值的方法
    getPicker() {
      this.$api.uploadcommoditiesd.getPicker().then((res) => {
        console.log(res)
        // let arr = Object.values(res.data)
        let arr = res.data.map((item) => {
          return item["text"]
        })
        this.columns = arr.slice(1)
      })
    },

    onClickLeft() {
      this.$router.push("/myshop")
    },

    // 这是picker选择的值
    onConfirm(value) {
      this.value = value
      console.log(value)
      this.showPicker = false
    },

    // 上传
    upload() {
      if (
        !(this.formData.title && this.formData.des && this.fileList.length > 0)
      ) {
        Toast("请完善新闻信息")
      } else {
        console.log(this.fileList)
        let files = this.fileList
        let self = this
        self.isLoading = true
        self.isloadingText = "加载中..."

        async function uploadImage() {
          try {
            for (let i = 0; i < files.length; i++) {
              self.fileList[i].status = "uploading"
              self.fileList[i].message = "上传中"
              let name = files[i].file.name
              let index = name.lastIndexOf(".")
              let ext = name.substr(index + 1)
              const result = await client.put(
                "news/" + new Date().getTime() + i + "." + ext,
                files[i].file
              )
              //返回的图片路径
              self.image_urls[i] = result.url
              self.fileList[i].status = "success"
              self.fileList[i].message = "上传成功"
            }
            console.log(self.image_urls)
            self.formData.pic = self.image_urls[0]
            let picObj = { imgs: self.image_urls }
            Object.assign(self.formData, picObj)
            console.log(self.formData)
            // 获取审核token
            // self.examineBothTwo()

            // 请求接口
            self.$api.news.putData(self.formData).then((res) => {
              console.log(res)
              if (res.code == 200) {
                Toast("发布成功")
                self.fileList = []
                self.formData.title = ""
                self.formData.des = ""
              } else {
                Toast("发布失败")
              }
            })

            self.isLoading = false
            self.isloadingText = "发布新闻"
          } catch (e) {
            console.log(e)
            Toast("图片上传失败！")
          }
        }
        // 调用上传
        if (files.length > 0) uploadImage()
      }
    },

    afterRead(file) {
      console.log(file)
      if (this.fileList.length > 6) {
        Toast("最多选择6张图片")
        return
      }
      this.readflag = true
    },
  },
}
</script>

<style lang="less" scoped>
.uploadcommoditiesd {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .main {
    flex: 1;
    background-color: #edf1f8;

    .content {
      margin: 0 auto;
      // background-color: pink;
      width: 90%;
      height: 100%;
      margin-top: 1.25rem /* 20/16 */;
    }
  }

  .footer {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    margin-top: 1.25rem /* 20/16 */;
    width: 100%;
    height: 6.875rem /* 110/16 */ /* 120/16 */ /* 100/16 */ /* 50/16 */;
    // background-color: pink;
  }

  .reslut {
    color: red;
  }
}
</style>
